package com.example.nccdeploytool.controller;

import com.example.nccdeploytool.entity.FileEntity;
import com.example.nccdeploytool.util.FileUtil;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.WritableImage;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.GridPane;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class HelloControllerBak implements Initializable {
    @FXML
    private Label welcomeText;

    @FXML
    private GridPane root;

    @FXML
    private ListView lvSrcFront;
    @FXML
    private TextField txtSrcFront;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        try {
            List<String> allFiles = FileUtil.getAllFiles(txtSrcFront.getText());

            List<FileEntity> list = allFiles.stream().map(x -> {
                FileEntity fileEntity = new FileEntity();
                fileEntity.setFilePath(x);
                fileEntity.setFilePathShow(x.replace(txtSrcFront.getText(), "."));
                return fileEntity;
            }).toList();

            System.out.println(allFiles.toString());

            lvSrcFront.getItems().addAll(list.stream().map(x -> x.getFilePathShow()).toList());

            setupListView(lvSrcFront);


            // 监听Scene尺寸变化
            root.sceneProperty().addListener((observable, oldScene, newScene) -> {
                if (newScene != null) {
                    newScene.widthProperty().addListener((obs, oldWidth, newWidth) -> {
                        System.out.println("Scene宽度变化: " + newWidth);
                        lvSrcFront.refresh();
                    });

                    newScene.heightProperty().addListener((obs, oldHeight, newHeight) -> {
                        System.out.println("Scene高度变化: " + newHeight);
                        // 处理高度变化逻辑
                        lvSrcFront.refresh();
                    });
                }
            });


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 设置拖拽
     */
    public void setupListView(ListView listView) {
        listView.setCellFactory(lv -> {
            ListCell<String> cell = new ListCell<String>() {
                private final Label label = new Label();

                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty || item == null) {
                        setGraphic(null);
                    } else {
                        label.setText(item);
                        label.setWrapText(true);  // 关键设置：启用自动换行
                        label.setMaxWidth(listView.getWidth() - 30);  // 设置最大宽度
                        setGraphic(label);
                    }
                }
            };

            // 拖拽开始
            cell.setOnDragDetected(event -> {
                if (!cell.isEmpty()) {

                    // 创建拖拽图像
                    WritableImage snapshot = cell.snapshot(null, null);

                    Dragboard dragboard = cell.startDragAndDrop(TransferMode.MOVE);
                    ClipboardContent content = new ClipboardContent();
                    content.putString(cell.getItem());
                    dragboard.setDragView(snapshot);
                    dragboard.setContent(content);

                    // 半透明效果
                    cell.setOpacity(0.5);
                    event.consume();

                }
            });

            // 拖拽进入
            cell.setOnDragEntered(event -> {
                if (event.getGestureSource() != cell &&
                        event.getDragboard().hasString()) {
                    cell.setStyle("-fx-background-color: #d0d0d0;");
                }
                event.consume();
            });

            // 拖拽离开
            cell.setOnDragExited(event -> {
                cell.setStyle("");
                event.consume();
            });

            // 拖拽结束
            cell.setOnDragDone(event -> {
                cell.setOpacity(1.0);
                event.consume();
            });

            return cell;
        });

        // 拖拽放置（精确到项之间）
        listView.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;

            if (db.hasString()) {
                ObservableList<String> items = listView.getItems();
                String draggedItem = db.getString();
                int draggedIndex = items.indexOf(draggedItem);

                // 获取鼠标位置对应的项索引
                int dropIndex = listView.getSelectionModel().getSelectedIndex();
                if (dropIndex == -1) {
                    dropIndex = items.size() - 1;
                }

                // 计算放置位置（上方或下方）
                double y = event.getY();
                ListCell<String> cell = (ListCell<String>) listView.lookup(".list-cell");
                if (cell != null && y > cell.getHeight() / 2) {
                    dropIndex++;
                }

                if (draggedIndex >= 0 && draggedIndex != dropIndex) {
                    items.remove(draggedIndex);
                    if (dropIndex > draggedIndex) {
                        dropIndex--;
                    }
                    items.add(dropIndex, draggedItem);
                    success = true;
                }
            }
            event.setDropCompleted(success);
            event.consume();
        });
    }


    @FXML
    protected void onHelloButtonClick() {
        welcomeText.setText("Welcome to JavaFX Application!");
    }


}